package com.ksd.control;

import com.alibaba.fastjson.JSONObject;
import com.ksd.control.result.BaseResult;
import com.ksd.control.result.RegisterResult;
import com.ksd.control.result.ResultParam;
import com.ksd.dao.IUserDAO;
import com.ksd.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;

@Controller()
public class UserAction extends BaseAction {
    @Autowired
    private IUserDAO userDAO;

    private List userList;
    private String delete;
    private String registerUser;

    public List getUserList() {
        return userList;
    }

    public void setUserList(List userList) {
        this.userList = userList;
    }

    public String getRegisterUser() {
        return registerUser;
    }

    public void setRegisterUser(String registerUser) {
        this.registerUser = registerUser;
    }

    public String getDelete() {
        return delete;
    }

    public void setDelete(String delete) {
        this.delete = delete;
    }

    public String register() {
        User user = JSONObject.parseObject(registerUser, User.class);
        if (userDAO.isExist(user.getUsername())) {
            setResult(new RegisterResult().setResult(ResultParam.FAILURE).setMessage("用户名已存在"));
        } else {
            userDAO.insertUser(user);
            setResult(new RegisterResult().setResult(ResultParam.SUCCESS).setMessage("注册成功"));
        }
        return SUCCESS;
    }

    public String list() {
        userList = userDAO.getUsers();
        return SUCCESS;
    }

    public String delete() {
        User user = JSONObject.parseObject(delete, User.class);
        userDAO.deleteUser(String.valueOf(user.getId()));
        setResult(new BaseResult().setResult(ResultParam.SUCCESS));
        return SUCCESS;
    }
}
